<template>
    <div class="postDeatil">
        <div class="detailTop">
            <i class="iconfont icon-xiangzuojiantou" @click="back"></i>
            <p>每日乐圈</p>
            <Report :bodyId="$route.params.bodyId" :reportedId="userId"/>
        </div>
        <div class="detailCenter">
            <div class="post">
                <div class="top">
                    <router-link :to="`/themself/${userId}`">
                        <van-image 
                            width="1rem" 
                            height="1rem" 
                            radius="100%" 
                            fit="cover" 
                            :src="img"
                        />
                        <div class="nameTime">
                            <p>{{name}}</p>
                            <p>{{time}}</p>
                        </div>
                    </router-link>
                    <button v-if="isMelf !== true" @click="follow" :class="followName">{{followName === 'notFollow' ? '关注' :'已关注'}}</button>
                </div>
                <div class="font">
                    {{content}}
                </div>
                <div class="pic">
                    <van-image 
                        v-for="(img,index) in imgs"
                        :key="index"
                        width="3rem"
                        height="3rem"
                        fit="cover" 
                        :src="img" 
                        @click="preview(index)"
                    />
                </div>
                <div class="tag">
                    <a href="javascript:;"># {{className}}</a>
                </div>
                <div class="bottom">
                    <Like :like="like" :postId="$route.params.bodyId" :className="className" :postContent="content" :userId="userId"></Like>
                    <Love :love="love" :postId="$route.params.bodyId" :className="className" :postContent="content" :userId="userId"></Love>
                </div>
            </div>
            <div class="chat">
                <div class="chatTop">
                    <p>全部评论</p>
                </div>
                <div class="chatMain">
                    <p v-if="empty === true">无评论</p>
                    <AComment ref="Acomment"
                        v-for="(comment,index) in comments" 
                        :key="index"
                        :commentId="comment.commentId"
                        :context="comment.context"
                        :img="comment.img"
                        :nickname="comment.nickname"
                        :time="comment.time"
                        :userId="comment.userId"
                        :landId="userId"
                        :sonNumber="comment.sonNumber"
                        :isMself="comment.userId == decode.userId"
                        :postId="$route.params.bodyId"
                    />
                </div>
            </div>
        </div>
        <CommentButton ref="commentBtn" :isPost="isPost" :postUserId="userId" :bodyId="$route.params.bodyId" :bodyMessage="content"/>
    </div>
</template>

<script>
import axios from 'axios'
import Like from './Like.vue'
import Love from './Love.vue'
import Report from './Report.vue'
import Talk from './Talk.vue'
import { ImagePreview, Toast } from 'vant';
import AComment from './AComment.vue'
import jwtDecode from 'jwt-decode'
import CommentButton from './CommentButton.vue'
export default {
    name:'PostDetail',
    components:{
        Like,Love,Report,Talk,AComment,CommentButton,
        [ImagePreview.Component.name]: ImagePreview.Component,
    },
    data() {
        return {
            login:null,
            decode:null,
            followName:'notFollow',
            isMelf:null,//判断这个帖子是不是自己的
            isPost:true,//判断是不是帖子
            like:null,
            time:null,
            love:null,
            className:null,
            postId:null,
            imgs:[],
            img:null,
            content:null,
            name:null,
            userId:null,
            // 以下是评论相关数据
            comments:null,
            empty:false
        }
    },
    updated(){
        let ele = document.getElementsByClassName('detailCenter')[0];
        ele.scrollTop = ele.scrollHeight;
        if(this.$refs.Acomment){
            for(let i = 0;i < this.$refs.Acomment.length;i++){
                this.$refs.Acomment[i].$on('changeComments',this.changeComments)
            }
        }
    },
    mounted() {
        if(sessionStorage.getItem('token')){
            let token=sessionStorage.getItem("token")
            this.decode = jwtDecode(token);
            this.login = true
        }else{
            this.login = false
            this.followName = 'notFollow'
        }
        //注册自定义事件
        this.$refs.commentBtn.$on('changeComments',this.changeComments)
        const postId = this.$route.params.bodyId
        //查看帖子详情
        axios({
            url:'/body/findBody',
            method:'get',
            params:{
                bodyId:postId
            }
        }).then(data=>{
            const res = data.data.data
            // console.log(res)
            this.img = res.img
            this.like = res.praise
            this.love = res.collection,
            this.className = res.classname
            this.time = res.time
            if(res.imgs){
                this.imgs = res.imgs.split(',')
            }else{
                this.imgs = null
            }
            this.postId = res.postId
            this.content = res.content
            this.name = res.nickname
            this.userId = res.userId
            if(this.login){
                if(this.decode.userId === this.userId){
                    this.isMelf = true
                }
            }else{
                this.isMelf = false
            }
            if(this.login){
                //检查用户有没有关注这个人
                axios({
                    url:'/follow/judgeFollow',
                    method:'get',
                    headers:{
                        'Authentication-Token':JSON.parse(sessionStorage.getItem("token"))
                    },
                    params:{
                        userId:this.decode.userId,
                        useredId:this.userId
                    }
                }).then(data=>{ 
                    // console.log(data)////////////////////
                    if(data.data.data === '您未关注此用户'){
                        this.followName = 'notFollow'
                    }else{
                        this.followName = 'isFollow'
                    }
    
                }).catch(err=>{
                    console.log(err)
                })
            }else{
                this.followName = 'notFollow'
            }
        }).catch((err)=>{
            console.log(err)
        })
        //查看帖子下的评论
        axios({ 
            url:'/praise/findComment',
            method:'get',
            params:{
                bodyId:postId,
            }
        }).then(data=>{
            console.log(data)
            let res = data.data.data
            this.comments = res
            if(res.length === 0){
                this.empty = true
            }else{
                this.empty = false
            }
            // console.log(res)
        }).catch(err=>{
            console.log(err)
        })
        
    },
    beforeRouteLeave(to, from, next) {
        //离开当前组件之前
        let main = document.getElementsByClassName('postDeatil')[0]
        // console.log(main.scrollTop)
        this.top = main.scrollTop || 0,
        next()
    },
    methods:{
        preview(index){
            ImagePreview({
                images: this.imgs,
                startPosition: index,
            });
        },
        back(){
            window.history.go(-1);
        },
        changeComments(value){
            // console.log(value) 
            this.comments = value
        },
        //添加关注
        follow(){
            if(this.login){
                const followParam = new URLSearchParams()
                followParam.append('userId',String(this.decode.userId))//关注人的id
                followParam.append('useredId',String(this.userId))//被关注人的id
                axios({
                    url:'/follow/addFollow',
                    method:'post',
                    data:followParam,
                    headers:{
                       'Authentication-Token':JSON.parse(sessionStorage.getItem("token"))
                    }
                }).then(data=>{
                    if(data.data.data !== '成功关注'){
                        this.cancel()//取消关注
                    }else{
                        if(data.data.code === 20000){
                            console.log('关注成功')
                            this.followName = 'isFollow'
                            //给服务器发送消息
                            let sendParam = new URLSearchParams()
                            sendParam.append('bodyMessage',this.content)
                            sendParam.append('content',`${this.decode.nickname} 关注了你`)
                            sendParam.append('form',String(this.decode.userId))
                            sendParam.append('to',String(this.userId))
                            sendParam.append('username',this.decode.username)
                            sendParam.append('calsses',String(4))
                            axios({
                                method:'post',
                                url:'/body/sendMessage',
                                data:sendParam,
                                headers:{
                                    'Authentication-Token':JSON.parse(sessionStorage.getItem("token"))
                                }
                            }).then(data=>{
                                if(data.data.code === 20000){
                                    console.log('发送成功')
                                }
                            }).catch(err=>{
                                console.log(err)
                            })
                        }
                    }
                }).catch(err=>{
                    console.log(err)
                })
            }else{
                Toast('请先登录或注册')
            }
        },
        cancel(){
            const calcelParam = new URLSearchParams()
            calcelParam.append('userId',String(this.decode.userId))
            calcelParam.append('useredId',String(this.userId))
            axios({
                url:'/follow/deleteFollow',
                method:"DELETE",
                data:calcelParam,
                headers:{
                    'Authentication-Token':JSON.parse(sessionStorage.getItem("token"))
                }
            }).then(data=>{//取消关注之后
                if(data.data.code === 20000){
                    console.log('取消关注')
                    this.followName = 'notFollow'
                }
            }).catch(err=>{
                console.log(err)
            })
        }   
    }
}
</script>

<style lang="less" scoped>
    .isFollow{ 
        color: var(--themeColor);
        background-color: white;
        border-color: var(--themeColor) !important;
    }
    .notFollow{
        border-color: var(--themeColor) !important;
        color: white;
        background-color: var(--themeColor) ;
    }

    .postDeatil{
        display: flex;
        flex-direction: column;
        height: 100vh;
        .detailTop{
            padding: 0.2rem 0.3rem;
            display: flex;
            justify-content: space-between;
            font-size: 0.4rem;
            border-bottom: solid 1px #f0f0f0;
        }
        .detailCenter{
            flex: 1;
            overflow-y: scroll;
            // padding: 0 0.3rem;
            .post{
                padding-top: 0.3rem;
                .top{
                    display: inline-flex;
                    justify-content: space-between;
                    flex-direction: row;
                    padding-bottom: 0.2rem;
                    width: 100%;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    a{
                        display: flex;
                        align-items: center;
                        color: #4b4b4b;
                        font-size: 0.4rem;
                        .nameTime{
                            p{
                                margin-left: 0.1rem;
                                &:nth-child(2){
                                    font-size: 0.2rem;
                                    color: #a1a1a1;
                                }
                            }
                        }
                    }
                    button{
                        height: 0.8rem;
                        border-radius: 0.5rem;
                        border: solid 1px black;
                        padding: 0.1rem 0.4rem;
                        font-size: 0.28rem;
                    }
                }
                .font{
                    margin-bottom: 0.2rem;
                    font-size: @fontSmall;
                }
                .pic{
                    display: flex;
                    flex-wrap: wrap;
                    justify-content: space-evenly;
                    
                    .van-image{
                        margin-right: 0.15rem;
                        margin-bottom: 0.2rem;
                    }
                    
                }
                .tag{
                    a{
                        padding: 0.05rem 0.15rem;
                        display: inline-block;
                        border-radius: 10px;
                        border: solid 1px var(--themeColor);
                        color: var(--themeColor);
                    }
                }
                .bottom{
                    padding: 0.2rem 0;
                    display: flex;
                    justify-content: space-evenly;
                    margin: 0.2rem 0;
                    margin-bottom: 0;
                    border-bottom: solid 1px #f0f0f0;
                }
            }
            .chat{
                .chatTop{
                    border-bottom: solid 1px #f0f0f0;
                    padding: 0.2rem 0;
                    background-image: linear-gradient(to bottom right,white, #f8f8f8);
                    p{
                        font-size: 0.4rem;
                        text-indent: 0.3rem;
                    }
                }
            }
        }
        
    }
</style>